package com.jgp.third.pay.controller;

import com.jgp.sys.controller.JGPBackController;
import com.jgp.common.utils.JGPUtil;
import com.jgp.common.utils.ReflectUtil;
import com.jgp.third.pay.model.PaymentConfig;
import com.jgp.third.pay.pojo.NormalBatchTransInfo;
import com.jgp.third.pay.pojo.NormalOrderInfo;
import com.jgp.third.pay.pojo.PayOverOrderInfo;
import com.jgp.third.pay.utils.PayUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 项目   jgp-cloud-parent
 * 作者   loufei
 * 时间   2018/10/24
 */
@Controller
@RequestMapping("/third/pay/aliPayController")
public class AliPayController extends JGPBackController {
    
    private static Logger logger = LoggerFactory.getLogger(AliPayController.class);
    
    @Value("${jgp.pay.callback-class}")
    private String callbackClass;
    
    @RequestMapping("doPay")
    public void doPay(@ModelAttribute("orderInfo") NormalOrderInfo orderInfo,
                      @ModelAttribute("extParamMap") String extParamMap,
                      @ModelAttribute("callbackParamMap") String callbackParamMap,
                      @ModelAttribute("paymentConfig") PaymentConfig paymentConfig,
                      HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print(PayUtil.invokePayFormPage(paymentConfig, orderInfo, JGPUtil.jsonToMap(extParamMap),
                                            JGPUtil.jsonToMap(callbackParamMap)
        ));
    }
    
    @RequestMapping("doBatchTrans")
    public void doBatchTrans(@ModelAttribute("callbackParamMap") String callbackParamMap,
                             @ModelAttribute("normalBatchTransInfo") NormalBatchTransInfo normalBatchTransInfo,
                             @ModelAttribute("details") String details,
                             @ModelAttribute("paymentConfig") PaymentConfig paymentConfig,
                             HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        
        if(Objects.nonNull(details)){
            List<Map> detailList = JGPUtil.jsonToList(details,HashMap.class);
            String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            StringBuilder sb = new StringBuilder();
            for (int no = 0; no < detailList.size(); no++) {
                Map detailInfo = detailList.get(no);
                sb.append(now+String.format("%05d", no));
                sb.append("^");
                sb.append(detailInfo.get("account"));
                sb.append("^");
                sb.append(detailInfo.get("name"));
                sb.append("^");
                sb.append(detailInfo.get("money"));
                sb.append("^");
                sb.append(detailInfo.get("remark"));
                if(detailList.size()>1&&no < detailList.size()-1){
                    sb.append("|");
                }
            }
            normalBatchTransInfo.setDetailsInfo(sb.toString());
            out.print(PayUtil.invokeBatchTransFormPage(paymentConfig,normalBatchTransInfo, null));
        }
    }
    
    @RequestMapping("payReturn")
    public String payReturn(RedirectAttributes attr, HttpServletRequest request) {
        String orderNo = request.getParameter("out_trade_no");
        String no = request.getParameter("trade_no");
        String money = request.getParameter("total_amount");
        String sellerId = request.getParameter("seller_id");//商户ID
        Map<String, Object> params = new HashMap<>();
        params.put("orderNo", orderNo);
        params.put("no", no);
        params.put("money", money);
        params.put("sellerId", sellerId);
        Map<String, Object> origin = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            origin.put(name, valueStr);
        }
        params.put("origin", origin);
        try {
            if (StringUtils.isNotBlank(callbackClass)) {
                ReflectUtil.invoke(callbackClass, "payReturn", new Class[]{Map.class}, params);
            }
        } catch (ClassNotFoundException | InvocationTargetException | IllegalAccessException |
                InstantiationException e) {
            e.printStackTrace();
            logger.error("回调类异常，检查回调类是否配置正常", e);
        }
        PayOverOrderInfo orderInfo = JGPUtil.merge(new PayOverOrderInfo(), params);
        attr.addFlashAttribute("orderInfo", orderInfo);
        return "redirect:/third/pay/payController/payReturn";
    }
    
    public static void main(String[] args) {
        System.out.println(String.format("%05d", 1));
        System.out.println(String.format("%05d", 10));
    }
}
